package com.platform.qujia.service.impl;

import com.platform.qujia.dao.*;
import com.platform.qujia.enums.CardRechargeRecordEnum;
import com.platform.qujia.enums.WxTemplateEnum;
import com.platform.qujia.pojo.*;
import com.platform.qujia.service.FleetCardService;
import com.platform.qujia.service.PayOrderService;
import com.platform.qujia.utils.StringUtils;
import com.platform.qujia.utils.exception.CustomException;
import com.platform.qujia.utils.weixinapp.WxPushUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class FleetCardServiceImpl implements FleetCardService {
    private static Logger logger = (Logger) LoggerFactory.getLogger(FleetCardServiceImpl.class);

    @Resource
    private FleetCardMapper fleetCardMapper;

    @Autowired
    private PayOrderService payOrderService;

    @Resource
    private WxPushUtil wxPushUtil;

    @Resource
    private AppUserInfoMapper appUserInfoMapper;

    @Resource
    private OilMapper oilMapper;

    @Resource
    private FleetCardRechargeRecordMapper fleetCardRechargeRecordMapper;

    @Resource
    private FleetCardSubMapper fleetCardSubMapper;

    @Override
    public FleetCard selectFleetCardByCardNumber(String cardNumber) {
        return fleetCardMapper.selectFleetCardByCardNumber(cardNumber);
    }

    @Override
    public int updateFleetCard(FleetCard fleetCard) {
        return fleetCardMapper.updateFleetCard(fleetCard);
    }

    @Override
    public List<FleetCard> selectFleetCardByKeyword(Long enterpriseId, String keyword) {
        return fleetCardMapper.selectFleetCardByKeyword(enterpriseId, keyword);
    }

    @Override
    public FleetCard selectById(Long fleetCardId) {
        return fleetCardMapper.selectById(fleetCardId);
    }

    @Override
    public PayOrder cdkPay(FleetCard fleetCard, Station station, PayOrder payOrder) {
        BigDecimal orderAmt = BigDecimal.valueOf(payOrder.getAmt());
        if (ObjectUtils.notEqual(fleetCard.getEnterpriseId(), Long.valueOf(station.getEnterpriseId())))
            throw new CustomException("该车队卡不归属于该油企/油站", 1001);
        if (fleetCard.getBalance().compareTo(orderAmt) < 0)
            throw new CustomException("该车队卡余额不足", 1001);
        //Map<String,Object> amountMap = reductionActivityService.selectReductionByPayOrder(appUserInfo, newPayOrder, "CSP", request, station);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //车队卡立减，五期的内容
        //BigDecimal discountAmt=payOrderService.reductionActivitiesAmountCalculation(activitiesVO);

        AppUserInfo appUserInfo=new AppUserInfo();
        appUserInfo.setMobilePhone(fleetCard.getPhone());
        appUserInfo.setStationId(fleetCard.getEnterpriseId().intValue());
        List<AppUserInfo> appUserInfos = appUserInfoMapper.selectAppUserInfoByMobilePhoneAndStationId(appUserInfo);
        if(appUserInfos.size()>0){
            Integer userId = appUserInfos.get(0).getUserId();
            payOrder.setConsumerId(userId);// 车队卡id
        }

        FleetCard updateFleetCard = new FleetCard();
        updateFleetCard.setId(fleetCard.getId());
        updateFleetCard.setBalance(fleetCard.getBalance().subtract(orderAmt));
        updateFleetCard.setUpdatedTime(new Date());
        updateFleetCard(updateFleetCard);
        payOrder.setCdkType(FleetCard.cdkType_fleet_card);
        payOrder.setConsumer(fleetCard.getFleetName());       //客户昵称
        payOrder.setCustomerPhone(fleetCard.getPhone());
        payOrder.setCdkId(fleetCard.getId());// 车队卡id
        payOrder.setEnterpriseName(station.getEnterprise().getEnterpriseName());
        payOrder.setBalance(updateFleetCard.getBalance()); // 保存车队卡余额
        gzhPaySuccessPush(fleetCard,updateFleetCard,payOrder);
        // 生成车队卡主卡消费记录
        fleetCardRechargeRecord(fleetCard,payOrder,updateFleetCard);
        return payOrder;
    }

    // 生成车队卡主卡消费记录
    private void fleetCardRechargeRecord(FleetCard fleetCard, PayOrder payOrder, FleetCard updateFleetCard){
        FleetCardRechargeRecord fleetCardRechargeRecord = new FleetCardRechargeRecord();
        fleetCardRechargeRecord.setEnterpriseId(fleetCard.getEnterpriseId());
        fleetCardRechargeRecord.setFleetCardId(fleetCard.getId());
        // 消费金额
        fleetCardRechargeRecord.setRechargeAmount(BigDecimal.valueOf(payOrder.getAmt()));
        fleetCardRechargeRecord.setGiftAmount(BigDecimal.ZERO);
        fleetCardRechargeRecord.setBalance(fleetCard.getBalance());
        fleetCardRechargeRecord.setAfterBalance(updateFleetCard.getBalance());
        fleetCardRechargeRecord.setCreatedTime(new Date());
        fleetCardRechargeRecord.setStationId(payOrder.getStationId().longValue());
        fleetCardRechargeRecord.setCardType(CardRechargeRecordEnum.CONSUMPTION_XF.getValue());
        fleetCardRechargeRecord.setFleetOrderNo(payOrder.getOrderNo());
        fleetCardRechargeRecord.setOilId(Long.valueOf(payOrder.getOilName()));

        // 共享模式下，使用主卡消费，但是同样记录子卡id
        if(Objects.nonNull(fleetCard.getFleetCardSubId()))      {
            fleetCardRechargeRecord.setFleetCardSubId(fleetCard.getFleetCardSubId());
            FleetCardSubVo fleetCardSubVo = fleetCardSubMapper.selectFleetCardSubById(fleetCard.getFleetCardSubId());
            fleetCardRechargeRecord.setUserName(fleetCardSubVo.getName());
            AppUserInfo appUser = appUserInfoMapper.getAppUserById(fleetCardSubVo.getAppUserId());
            fleetCardRechargeRecord.setUserPhone(appUser.getMobilePhone());
        }else {
            FleetCard newFleetCard=this.selectById(fleetCard.getId());
            fleetCardRechargeRecord.setUserName(newFleetCard.getContacts());
            fleetCardRechargeRecord.setUserPhone(newFleetCard.getPhone());
        }

        fleetCardRechargeRecordMapper.insertSelective(fleetCardRechargeRecord);
    }

    public void gzhPaySuccessPush(FleetCard fleetCard,FleetCard updateFleetCard,PayOrder payOrder){
        AppUserInfo appUserInfo=new AppUserInfo();
        appUserInfo.setMobilePhone(fleetCard.getPhone());
        appUserInfo.setStationId(fleetCard.getEnterpriseId().intValue());
        List<AppUserInfo> appUserInfos = appUserInfoMapper.selectAppUserInfoByMobilePhoneAndStationId(appUserInfo);

        if(appUserInfos.size()>0){
            appUserInfo=appUserInfos.get(0);
            Map<String, String> templateParams = new HashMap<>();
            templateParams.put("openid", appUserInfo.getBlogOpenid());
            String string = payOrder.getStationName() + ",持卡人:" + fleetCard.getContacts();
            if(string.length() > 20){
                string = string.substring(0,17) + "...";
            }
            templateParams.put("stationName", string);
            templateParams.put("oilName", payOrder.getOilName());
            if(StringUtils.isNotEmpty(payOrder.getOilName())){
                Oil oil = oilMapper.selectOilById(Long.valueOf(payOrder.getOilName()));
                templateParams.put("oilName", oil.getOilName());
            }
            templateParams.put("payDetail","实付" + payOrder.getAmt() + "元"+",优惠"+payOrder.getDiscountAmt()+"元");
            templateParams.put("walletBalance", updateFleetCard.getBalance().toString() + "元");
            logger.info("微信支付-微信模板参数：{}", templateParams);

            wxPushUtil.sendTemplateMsg(payOrder.getEnterpriseId(), templateParams, WxTemplateEnum.REFUEL_SUCCESS);
        }
    }
}
